import {ipcMain} from "electron";
import * as fs from "fs";
import {NOTES_DIR} from "@/electron/const";
import {exec} from "@/utils/main/cmd.shell.utils";
import {getGitAddress} from "@/utils/main/git.utils";
import {deleteFolderRecursive, DirTree} from "@/utils/main/file.uitls";
import {noticeMessageToRenderer, noticeRefreshNotesToRenderer} from "@/electron/helper";
import {syncNote} from "@/electron/git";

const path = require("path");

/**
 * 添加 git 笔记本，并创建 git 目录
 */
ipcMain.handle("addNote", async (e, {name, gitAddress, force = false}) => {
    const res = await exec(`git -C "${path.resolve(NOTES_DIR)}" clone ${gitAddress} ${name}`);
    noticeMessageToRenderer(res.success ? "成功添加笔记!" : `添加笔记失败！ ${res.message}`, res.success);
    noticeRefreshNotesToRenderer();
    return res.success;
});

/**
 * 获取 git 远程地址
 */
ipcMain.handle("getGitAddressHandler", async (e, dir) => {
    return await getGitAddress(dir);
});


// 同步笔记到 git
ipcMain.handle("syncNote", async (e, note: DirTree) => {
    const p = path.resolve(note.path);
    if (!fs.existsSync(p)) {
        return false;
    }
    return syncNote(note);
})